"""
Flask应用工厂
"""
from flask import Flask, request, jsonify
from flask_cors import CORS
from flask_jwt_extended import JWTManager, get_jwt_identity
from datetime import datetime, timedelta

from lemon_backend.config.settings import Config
from lemon_backend.api import api_bp, auth_bp
from lemon_backend.models import db_session, init_db, User

def create_app(config_class=Config):
    """
    创建并配置Flask应用实例

    Args:
        config_class: 配置类，默认为Config

    Returns:
        Flask应用实例
    """
    # 创建Flask应用
    app = Flask(__name__)

    # 加载配置
    app.config.from_object(config_class)

    # 配置CORS
    #CORS(app, resources={r"/api/*": {"origins": app.config['CORS_ORIGINS']}})
    #CORS(app)
    CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)

    # 初始化JWT
    jwt = JWTManager(app)

    # 注册JWT回调函数
    @jwt.token_verification_loader
    def verify_token(jwt_header, jwt_payload):
        # 获取用户ID
        user_id = jwt_payload['sub']

        # 查找用户
        user = User.query.get(user_id)

        # 如果用户不存在或已禁用，拒绝访问
        if not user or not user.is_active:
            return False

        # 如果用户没有last_login记录，允许访问
        if not user.last_login:
            return True

        # 检查最后登录时间是否超过30天
        one_month_ago = datetime.utcnow() - timedelta(days=30)
        if user.last_login < one_month_ago:
            return False

        return True

    # 初始化数据库
    init_db()

    # 注册蓝图
    app.register_blueprint(api_bp)
    app.register_blueprint(auth_bp)

    # 注册错误处理器
    register_error_handlers(app)

    # 注册请求钩子
    register_request_hooks(app)

    return app

def register_error_handlers(app):
    """
    注册错误处理器

    Args:
        app: Flask应用实例
    """
    @app.errorhandler(404)
    def not_found(error):
        """处理404错误"""
        return {"error": "Not Found", "message": str(error)}, 404

    @app.errorhandler(500)
    def internal_server_error(error):
        """处理500错误"""
        return {"error": "Internal Server Error", "message": str(error)}, 500

def register_request_hooks(app):
    """
    注册请求钩子

    Args:
        app: Flask应用实例
    """
    @app.before_request
    def log_request_info():
        """在请求处理前打印请求信息"""
        print(f"请求信息: {request.method} {request.path}")
        print(f"请求参数: {request.args}")
        if request.is_json:
            print(f"请求体(JSON): {request.get_json()}")
        print(f"请求头: {dict(request.headers)}")
        print("-" * 50)

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        """请求结束时关闭数据库会话"""
        db_session.remove()
